1363E - Tree Shuffling - CodeForces Solution


dfs and similar dp greedy trees *2000

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
#define int long long
using namespace std;
typedef pair<int,int> PII;
#define ft first
#define sd second
const int N=1e6+10;
const int mod=1e9+7;
int n,m,a[N],b[N],p[N],cnt1[N],cnt2[N],res;
vector<int>g[N];
void dfs(int u,int fa,int mn){
	for(auto v:g[u]){
		if(v==fa)continue;
		dfs(v,u,min(mn,p[u]));
		cnt1[u]+=cnt1[v];cnt2[u]+=cnt2[v];
	}
	if(p[u]<mn){
		int x=min(cnt1[u],cnt2[u]);
		cnt1[u]-=x;cnt2[u]-=x;
		res+=p[u]*x*2;
	}
}
void solve(){
	cin>>n;
	int cnt=0;
	for(int i=1;i<=n;i++){
		cin>>p[i]>>a[i]>>b[i];
		if(a[i]==1&&b[i]==0)cnt++,cnt1[i]++;
		else if(a[i]==0&&b[i]==1)cnt--,cnt2[i]++;
	}
	if(cnt){
		cout<<"-1\n";
		return;
	}
	for(int i=1;i<=n-1;i++){
		int x,y;cin>>x>>y;
		g[x].push_back(y);
		g[y].push_back(x);
	}
	dfs(1,0,0x3f3f3f3f);
	cout<<res<<'\n';
}
signed main(){
	ios::sync_with_stdio(false);cin.tie(0);
	int Case=1;
	//cin>>Case;
	while(Case--)solve();
}


Comments

Submit
0 Comments
More Questions

1718C - Tonya and Burenka-179
834A - The Useless Toy
1407D - Discrete Centrifugal Jumps
1095B - Array Stabilization
291B - Command Line Arguments
1174B - Ehab Is an Odd Person
624B - Making a String
1064C - Oh Those Palindromes
1471A - Strange Partition
1746A - Maxmina
1746B - Rebellion
66C - Petya and File System
1746C - Permutation Operations
1199B - Water Lily
570B - Simple Game
599C - Day at the Beach
862A - Mahmoud and Ehab and the MEX
1525A - Potion-making
1744D - Divisibility by 2n
1744A - Number Replacement
1744C - Traffic Light
1744B - Even-Odd Increments
637B - Chat Order
546C - Soldier and Cards
18D - Seller Bob
842B - Gleb And Pizza
1746D - Paths on the Tree
1651E - Sum of Matchings
19A - World Football Cup
630P - Area of a Star